package 对递归问题的分析.day01;

/**
 * <Description>
 *
 *  提供一种不需要返回值的解法
 *
 * @author wangxi
 */
public class WordSearch2 {

    boolean result = false;

    public boolean exist(char[][] board, String word) {
        if (word == null || word.length() <= 0) {
            return false;
        }
        char start = word.charAt(0);
        boolean[][] flag = new boolean[board.length][board[0].length];
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < board[i].length; j++) {
                if (start != board[i][j]) {
                    continue;
                }
                dfs(board, word, i, j, 0, flag);
                if (result) {
                    return true;
                }
            }
        }
        return false;
    }

    private void dfs(char[][] board, String word, int i, int j, int index, boolean[][] flag) {
        // index = 0的时，已经在这里过滤掉了
        if (i >= board.length || i < 0 || j < 0 || j >= board[i].length ||
                word.charAt(index) != board[i][j] || flag[i][j]) {
            return;
        }
        if (index == word.length() - 1) {
            result = true;
            return;
        }
        if (result) {
            return;
        }
        flag[i][j] = true;
        dfs(board, word, i + 1, j, index + 1, flag);
        dfs(board, word, i - 1, j, index + 1, flag);
        dfs(board, word, i, j + 1, index + 1, flag);
        dfs(board, word, i, j - 1, index + 1, flag);
        flag[i][j] = false;
    }
}

